package com.car.loan.project.cd.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.car.loan.common.enums.DeletedEnum;
import com.car.loan.common.utils.BeanUtils;
import com.car.loan.common.utils.IdCardUtil;
import com.car.loan.common.utils.SecurityUtils;
import com.car.loan.common.utils.StringUtils;
import com.car.loan.common.utils.qiniu.QiniuUtil;
import com.car.loan.framework.aspectj.lang.annotation.Log;
import com.car.loan.framework.aspectj.lang.enums.BusinessType;
import com.car.loan.framework.web.domain.AjaxResult;
import com.car.loan.project.cd.domain.CdCredit;
import com.car.loan.project.cd.domain.CdCreditAlbum;
import com.car.loan.project.cd.domain.bo.CreditApplyInfoAddBo;
import com.car.loan.project.cd.domain.bo.CreditApplyInfoUpdateBo;
import com.car.loan.project.cd.domain.bo.CreditInputInfoUpdateBo;
import com.car.loan.project.cd.domain.select.CreditBaseSelect;
import com.car.loan.project.cd.domain.vo.CreditAlbumVo;
import com.car.loan.project.cd.domain.vo.CreditApplyInfoVo;
import com.car.loan.project.cd.domain.vo.CreditBaseVo;
import com.car.loan.project.cd.domain.vo.CreditInputInfoVo;
import com.car.loan.project.cd.service.ICdCreditAlbumService;
import com.car.loan.project.cd.service.ICdCreditService;
import com.car.loan.project.cd.util.enums.CreditAlbumType;
import com.car.loan.project.cd.util.enums.CreditStatus;
import com.car.loan.project.xr.util.RedisDataUtil;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author huangding
 * @description
 * @date 2019/10/28 20:36
 */

@RestController
@RequestMapping("credit")
@Api(value = "征信管理", tags = "征信管理")
public class CreditController {

    @Autowired
    private ICdCreditService cdCreditService;

    @Autowired
    private ICdCreditAlbumService creditAlbumService;

    @Autowired
    private QiniuUtil qiniuUtil;

    @Autowired
    private RedisDataUtil redisDataUtil;

    @PreAuthorize("@ss.hasPermi('cd:credit:list')")
    @GetMapping("applyList")
    @ApiOperation(value = "征信申请列表", response = CreditBaseVo.class, responseContainer = "list")
    public AjaxResult getApplyList(@Valid CreditBaseSelect creditBaseSelect) {
        if (null == creditBaseSelect.getStatus()) {
            creditBaseSelect.setStatus(CreditStatus.INIT.status);
        }
        if (CreditStatus.COMPLETE.status == creditBaseSelect.getStatus()) {
            LocalDate localDate = LocalDate.now().minusDays(60);
            creditBaseSelect.setStartQueryDate(localDate.toString());
        }
        return AjaxResult.success(cdCreditService.findCreditBasePage(creditBaseSelect));
    }


    @PreAuthorize("@ss.hasPermi('cd:credit:query')")
    @GetMapping(value = "apply/{creditId}")
    @ApiOperation(value = "获取征信详情", response = CreditApplyInfoVo.class)
    public AjaxResult getApplyInfo(@PathVariable Long creditId) {
        CdCredit cdCredit = cdCreditService.selectCdCreditById(creditId);
        if (null == cdCredit) {
            return AjaxResult.error("无该征信信息");
        }
        CreditApplyInfoVo creditApplyInfoVo = new CreditApplyInfoVo();
        BeanUtils.copyBeanProp(creditApplyInfoVo, cdCredit);
        creditApplyInfoVo.setId(String.valueOf(cdCredit.getId()));

        CdCreditAlbum cdCreditAlbumQuery = new CdCreditAlbum();
        cdCreditAlbumQuery.setCreditId(creditId);
        List<CdCreditAlbum> cdCreditAlbums = creditAlbumService
            .selectCdCreditAlbumList(cdCreditAlbumQuery);

        if (StringUtils.isNotEmpty(cdCreditAlbums)) {
            List<CreditAlbumVo> imageAlbumVos = Lists.newArrayList();
            List<CreditAlbumVo> videoAlbumVos = Lists.newArrayList();
            for (CdCreditAlbum cdCreditAlbum : cdCreditAlbums) {
                if (CreditAlbumType.IMAGE.type == cdCreditAlbum.getType()) {
                    imageAlbumVos.add(new CreditAlbumVo().setId(cdCreditAlbum.getId())
                        .setUrl(qiniuUtil.getAuthUrl(cdCreditAlbum.getUrl()))
                        .setThumbnailUrl(qiniuUtil.getUrlByThumbnailHttps(cdCreditAlbum.getUrl()))
                        .setDbUrl(cdCreditAlbum.getUrl()));
                } else if (CreditAlbumType.VIDEO.type == cdCreditAlbum.getType()) {
                    videoAlbumVos.add(new CreditAlbumVo().setId(cdCreditAlbum.getId())
                        .setUrl(qiniuUtil.getAuthUrlOriginal(cdCreditAlbum.getUrl()))
                        .setDbUrl(cdCreditAlbum.getUrl()));
                }
            }
            creditApplyInfoVo.setImages(imageAlbumVos);
            creditApplyInfoVo.setVideos(videoAlbumVos);
        }

        creditApplyInfoVo.setAdminName(redisDataUtil.getAdminName(creditApplyInfoVo.getAdminId()));
        creditApplyInfoVo.setDeptName(redisDataUtil.getDeptName(creditApplyInfoVo.getDeptId()));

        return AjaxResult.success(creditApplyInfoVo);
    }

    @PreAuthorize("@ss.hasPermi('cd:credit:add')")
    @PostMapping("apply")
    @Log(title = "添加征信申请", businessType = BusinessType.INSERT)
    @ApiOperation("添加征信申请")
    public synchronized AjaxResult saveApply(
        @RequestBody @Valid CreditApplyInfoAddBo creditApplyInfoAddBo) {
        creditApplyInfoAddBo.setIdCardNo(creditApplyInfoAddBo.getIdCardNo().toUpperCase());
        if (!IdCardUtil.idCardValidate(creditApplyInfoAddBo.getIdCardNo())) {
            return AjaxResult.error("身份证格式错误");
        }
        //验证15天内是否有重复客户申请
        CdCredit cdCreditQuery = new CdCredit();
        cdCreditQuery.setIdType(creditApplyInfoAddBo.getIdType());
        cdCreditQuery.setBankId(creditApplyInfoAddBo.getBankId());
        cdCreditQuery.setIdCardNo(creditApplyInfoAddBo.getIdCardNo());
        QueryWrapper<CdCredit> queryWrapper = new QueryWrapper<>(cdCreditQuery);
        queryWrapper.gt("create_time", LocalDateTime.now().minusDays(15));
        List<CdCredit> cdCredits = cdCreditService.selectCdCreditQueryList(queryWrapper);
        if (StringUtils.isNotEmpty(cdCredits)) {
            return AjaxResult.error("该客户在15天内有重复申请，请联系管理员");
        }
        cdCreditService.save(creditApplyInfoAddBo);
        return AjaxResult.success();
    }

    @PreAuthorize("@ss.hasPermi('cd:credit:edit')")
    @PutMapping("apply")
    @Log(title = "编辑征信申请", businessType = BusinessType.UPDATE)
    @ApiOperation("编辑征信申请")
    public synchronized AjaxResult editApply(
        @RequestBody @Valid CreditApplyInfoUpdateBo creditApplyInfoUpdateBo) {
        creditApplyInfoUpdateBo.setIdCardNo(creditApplyInfoUpdateBo.getIdCardNo().toUpperCase());
        if (!IdCardUtil.idCardValidate(creditApplyInfoUpdateBo.getIdCardNo())) {
            return AjaxResult.error("身份证格式错误");
        }
        return cdCreditService.update(creditApplyInfoUpdateBo);
    }


    @PreAuthorize("@ss.hasPermi('cd:credit:withdraw')")
    @PutMapping("apply/withdraw/{creditId}")
    @Log(title = "撤回征信申请", businessType = BusinessType.WITHDRAW)
    @ApiOperation(value = "撤回征信申请", notes = "征信已录入不可撤回，status=10")
    public AjaxResult withdrawApply(@PathVariable Long creditId) {
        CdCredit cdCredit = cdCreditService.selectCdCreditById(creditId);
        if (null == cdCredit) {
            return AjaxResult.error("无该征信信息");
        }
        if (CreditStatus.SUBMIT.status != cdCredit.getStatus()) {
            return AjaxResult.error("当前状态不可撤回");
        }
        cdCredit.setStatus(CreditStatus.INIT.status);
        cdCredit.setOperateTime(LocalDateTime.now());
        cdCredit.setOperatorId(SecurityUtils.getLoginUserId());
        cdCreditService.updateCdCredit(cdCredit);
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('cd:credit:album:delete')")
    @DeleteMapping("album/{albumId}")
    @Log(title = "征信附件删除", businessType = BusinessType.DELETE)
    @ApiOperation("征信附件删除")
    public AjaxResult creditAlbumDelete(@PathVariable Long albumId) {
        creditAlbumService.deleteCdCreditAlbumById(albumId);
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('cd:apply:delete')")
    @DeleteMapping("apply/{creditId}")
    @Log(title = "征信申请删除", businessType = BusinessType.DELETE)
    @ApiOperation("征信申请删除")
    public AjaxResult creditDelete(@PathVariable Long creditId) {
        CdCredit cdCredit = cdCreditService.selectCdCreditById(creditId);
        if (cdCredit == null) {
            return AjaxResult.error("不存在");
        }
        if (CreditStatus.INIT.status != cdCredit.getStatus()) {
            return AjaxResult.error("当前状态不可删除");
        }
        cdCredit.setDeleted(DeletedEnum.DELETED.getCode());
        cdCreditService.updateCdCredit(cdCredit);
        return AjaxResult.success();
    }

    @GetMapping("inputList")
    @ApiOperation("征信录入列表")
    @PreAuthorize("@ss.hasPermi('cd:creditInput:query')")
    public AjaxResult getInputList(@Valid CreditBaseSelect creditBaseSelect) {
        if (null == creditBaseSelect.getStatus()) {
            creditBaseSelect.setStatus(CreditStatus.SUBMIT.status);
        }
        return AjaxResult.success(cdCreditService.findCreditBasePage(creditBaseSelect));
    }


    @PreAuthorize("@ss.hasPermi('cd:creditInput:query')")
    @GetMapping(value = "input/{creditId}")
    @ApiOperation(value = "获取征信录入详情", response = CreditInputInfoVo.class)
    public AjaxResult getInputInfo(@PathVariable Long creditId) {
        CdCredit cdCredit = cdCreditService.selectCdCreditById(creditId);
        if (null == cdCredit) {
            return AjaxResult.error("无该征信信息");
        }
        CreditInputInfoVo creditInputInfoVo = new CreditInputInfoVo();
        BeanUtils.copyBeanProp(creditInputInfoVo, cdCredit);

        creditInputInfoVo.setInputAdminName(redisDataUtil.getAdminName(cdCredit.getInputAdminId()));
        creditInputInfoVo
            .setSubmitAdminName(redisDataUtil.getAdminName(cdCredit.getSubmitAdminId()));

        CdCreditAlbum cdCreditAlbumQuery = new CdCreditAlbum();
        cdCreditAlbumQuery.setCreditId(creditId);
        List<CdCreditAlbum> cdCreditAlbums = creditAlbumService
            .selectCdCreditAlbumList(cdCreditAlbumQuery);

        if (StringUtils.isNotEmpty(cdCreditAlbums)) {
            List<CreditAlbumVo> imageAlbumVos = Lists.newArrayList();
            List<CreditAlbumVo> videoAlbumVos = Lists.newArrayList();
            for (CdCreditAlbum cdCreditAlbum : cdCreditAlbums) {
                if (CreditAlbumType.IMAGE.type == cdCreditAlbum.getType()) {
                    imageAlbumVos.add(new CreditAlbumVo().setId(cdCreditAlbum.getId())
                        .setUrl(qiniuUtil.getAdminAuthUrl(cdCreditAlbum.getUrl()))
                        .setThumbnailUrl(qiniuUtil.getUrlByThumbnail(cdCreditAlbum.getUrl()))
                        .setDbUrl(cdCreditAlbum.getUrl()));

                } else if (CreditAlbumType.VIDEO.type == cdCreditAlbum.getType()) {
                    videoAlbumVos.add(new CreditAlbumVo().setId(cdCreditAlbum.getId())
                        .setUrl(qiniuUtil.getAuthUrlOriginal(cdCreditAlbum.getUrl()))
                        .setDbUrl(cdCreditAlbum.getUrl()));
                }
            }
            creditInputInfoVo.setImages(imageAlbumVos);
            creditInputInfoVo.setVideos(videoAlbumVos);
        }
        creditInputInfoVo.setAdminName(redisDataUtil.getAdminName(creditInputInfoVo.getAdminId()));
        creditInputInfoVo.setDeptName(redisDataUtil.getDeptName(creditInputInfoVo.getDeptId()));
        creditInputInfoVo.setBankName(redisDataUtil.getBankName(creditInputInfoVo.getBankId()));
        return AjaxResult.success(creditInputInfoVo);
    }


    @PreAuthorize("@ss.hasPermi('cd:creditInput:edit')")
    @PutMapping("input")
    @Log(title = "征信录入", businessType = BusinessType.UPDATE)
    @ApiOperation("征信录入")
    public synchronized AjaxResult editInput(
        @Valid @RequestBody CreditInputInfoUpdateBo creditInputInfoUpdateBo) {
        return cdCreditService.input(creditInputInfoUpdateBo);
    }


    @PreAuthorize("@ss.hasPermi('cd:creditInput:withdraw')")
    @PutMapping("input/withdraw/{creditId}")
    @Log(title = "撤回征信录入", businessType = BusinessType.WITHDRAW)
    @ApiOperation(value = "撤回征信录入", notes = "status=10 才可撤回")
    public AjaxResult withdrawInput(@PathVariable Long creditId) {
        CdCredit cdCredit = cdCreditService.selectCdCreditById(creditId);
        if (null == cdCredit) {
            return AjaxResult.error("无该征信信息");
        }
        if (CreditStatus.COMPLETE.status != cdCredit.getStatus()) {
            return AjaxResult.error("当前状态不可撤回");
        }
        cdCredit.setStatus(CreditStatus.SUBMIT.status);
        cdCredit.setOperateTime(LocalDateTime.now());
        cdCredit.setOperatorId(SecurityUtils.getLoginUserId());
        cdCreditService.updateCdCredit(cdCredit);
        return AjaxResult.success();
    }


}
